package com.ruoyi.app.service.impl;

import com.ruoyi.app.dto.MemberCarDto;
import com.ruoyi.app.dto.MemberFeedbackDto;
import com.ruoyi.app.service.IAppMemberService;
import com.ruoyi.app.vo.ParkingCardVo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.domain.Member;
import com.ruoyi.domain.MemberCar;
import com.ruoyi.domain.MemberFeedback;
import com.ruoyi.domain.ParkingInfo;
import com.ruoyi.forest.WeChatClient;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.config.SmartParkingCloudConfig;
import com.ruoyi.mapper.MemberFeedbackMapper;
import com.ruoyi.mapper.MemberMapper;
import com.ruoyi.mapper.ParkingCardMapper;
import com.ruoyi.mapper.ParkingInfoMapper;
import com.ruoyi.service.IMemberCarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * App端Service业务层处理
 * 
 * @author dongdong
 * @date 2025-09-11
 */
@Slf4j
@Service
public class AppMemberServiceImpl implements IAppMemberService {

    private static final String DEFAULT_AVATAR = "https://zhtc.lssmartcity.com/profile/default-avatar.png";

    private static final String DEFAULT_NICKNAME = "微信用户";

    @Resource
    private WeChatClient weChatClient;
    @Resource
    private ParkingCardMapper parkingCardMapper;
    @Resource
    private MemberFeedbackMapper memberFeedbackMapper;
    @Resource
    private ParkingInfoMapper parkingInfoMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private IMemberCarService memberCarService;

    @Override
    public Member autoLogin(String code) {
        Map<String, Object> map = weChatClient.getWxXcxOpenid(SmartParkingCloudConfig.APPID_XCX, SmartParkingCloudConfig.SECRET_XCX, code);
        Optional.ofNullable(map.get("openid")).orElseThrow(() -> new RuntimeException("未获取到openid，请重试"));
        String openId = map.get("openid").toString();
        Member member = memberMapper.selectMemberByOpenId(openId);
        if (Objects.isNull(member)) {
            member = new Member();
            member.setOpenId(openId);
            member.setNickname(DEFAULT_NICKNAME);
            member.setAvatar(DEFAULT_AVATAR);
            memberMapper.insertMember(member);
        }
        return member;
    }


    @Override
    public List<ParkingCardVo> getMyParkCard(String uniqueId) {
        List<ParkingCardVo> list = parkingCardMapper.selectParkingCardByUniqueId(uniqueId);
        List<ParkingCardVo> voList = list.stream().map(e->{
            e.setValidDate(DateUtils.convertToChineseDate(e.getValidStartTime()));
            Date validDate = DateUtils.compareDates(e.getValidStartTime(), new Date()) > 0 ? e.getValidStartTime() : new Date();
            int validDay = DateUtils.differentDaysByMillisecond(validDate, e.getValidEndTime());
            e.setValidDay(validDay<0?0:validDay);
            // 1正常 2即将到期 3已到期
            e.setStatus(validDay<0?3:(validDay<10?2:1));
            e.setStatusName(validDay<0?"已到期":(validDay<10?"即将到期":"正常"));
            return e;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public int addFeedback(MemberFeedbackDto memberFeedbackDto) {
        MemberFeedback memberFeedback = new MemberFeedback();
        memberFeedback.setParkId(memberFeedbackDto.getParkId());
        memberFeedback.setMemberId(memberFeedbackDto.getMemberId());
        memberFeedback.setContent(memberFeedbackDto.getContent());
        memberFeedback.setImageUrl(memberFeedbackDto.getImageUrl());
        if(Objects.nonNull(memberFeedbackDto.getParkId())){
            ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(memberFeedbackDto.getParkId());
            memberFeedback.setDeptId(parkingInfo.getDeptId());
        }
        int res = memberFeedbackMapper.insertMemberFeedback(memberFeedback);
        if(res == 0){
            throw new RuntimeException("提交失败，请重试");
        }
        return res;
    }

    @Override
    public int addMemberCar(MemberCarDto memberCarDto) {
        if(Objects.isNull(memberCarDto.getMemberId()) || Objects.isNull(memberCarDto.getCarNumColor()) || Objects.isNull(memberCarDto.getCarNum())){
            throw new RuntimeException("查询参数异常！");
        }
        Member member = memberMapper.selectMemberById(memberCarDto.getMemberId());
        if(Objects.isNull(member)){
            throw new RuntimeException("会员信息不存在！");
        }
        if(StringUtils.isNotEmpty(memberCarDto.getCarNum())){
            MemberCar queryMemberCar = new MemberCar();
            queryMemberCar.setCarNum(memberCarDto.getCarNum());
            queryMemberCar.setMemberId(memberCarDto.getMemberId());
            List<MemberCar> list = memberCarService.selectMemberCarList(queryMemberCar);
            if(list.size() > 0){
                throw new RuntimeException("车牌已存在");
            }
        }
        MemberCar queryMemberCar = new MemberCar();
        queryMemberCar.setMemberId(memberCarDto.getMemberId());
        List<MemberCar> list = memberCarService.selectMemberCarList(queryMemberCar);
        if(list.size() > 10){
            throw new RuntimeException("最多添加10个车辆");
        }

        MemberCar memberCar = new MemberCar();
        memberCar.setMemberId(memberCarDto.getMemberId());
        memberCar.setCarNum(memberCarDto.getCarNum());
        memberCar.setCarNumColor(memberCarDto.getCarNumColor());
        memberCar.setIsNewEnergy(memberCarDto.getIsNewEnergy());
        int res = memberCarService.insertMemberCar(memberCar);
        if(res == 0){
            throw new RuntimeException("提交失败，请重试");
        }
        return res;
    }

}
